<template>
    <div class="inventory-container">
        <br />
        <el-card>
            <div class="page-common-top-filter">
                <div class="left">
                    <div class="page-common-filter-item">
                        <el-input v-model="skcFilter" class="page-common-filter-content" placeholder="SKC" />
                    </div>
                    <div class="page-common-filter-item">
                        <el-select v-model="curFilter" placeholder="最近出入库" class="page-common-filter-content">
                            <el-option v-for="item of curOptions" :value="item.value" :label="item.label"
                                :key="item.value" />
                        </el-select>
                    </div>
                    <div class="page-common-filter-item">
                        <el-select v-model="storeFilter" placeholder="仓库筛选" class="page-common-filter-content">
                            <el-option v-for="item of storeList" :value="item.addressId" :label="item.addressName"
                                :key="item.addressId" />
                        </el-select>
                    </div>
                </div>
                <div class="page-common-top-right-btn">
                    <el-button type="primary" @click="getInventoryList">搜索</el-button>
                    <el-button @click="onReset">重置</el-button>
                </div>
            </div>
        </el-card>
        <br />
        <el-card>
            <div class="page-common-top-filter">
                <el-button :disabled="!isActive" type="primary" @click="onAdd">新增</el-button>
                <!-- <el-button type="primary">导出</el-button> -->
                <span style="display: flex;align-items: center;margin: 0 10px;">库存合计数：{{ inventoryCount }}</span>
                <div class="page-common-top-right-btn">
                    <el-button type="primary" @click="onStoreAdd">仓库管理</el-button>

                    <el-button type="primary" :disabled="selectedItemList.length === 0"
                        @click="resetInventory">覆盖库存</el-button>
                    <el-button type="success" :disabled="selectedItemList.length === 0"
                        @click="reduceInventory">出库</el-button>
                    <el-button type="success" :disabled="selectedItemList.length === 0" @click="addInventory">入库</el-button>
                    <el-button @click="onClear">清空</el-button>
                </div>
            </div>
            <br />
            <el-table ref="tableRef" :data="inventoryList" style="width: 100%" class="table" :row-style="tableRowStyle"
                @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" />
                <el-table-column prop="skcId" label="SKC基本信息" width="300px">
                    <template #default="scope">
                        <div class="skc-data">
                            <img class="skc-img" :src="scope.row.skcImageUrl" />
                            <div class="skc-line">
                                <span>商品ID：{{ scope.row.skcId }}</span>
                                <span>商品名称：{{ scope.row.skcName }}</span>
                            </div>
                        </div>
                    </template>
                </el-table-column>
                <el-table-column label="SKU信息" width="800px" align="center">
                    <template #default="scope">
                        <el-table :data="scope.row.skuInfo">
                            <el-table-column prop="skuId" label="skuID" />
                            <el-table-column prop="skuName" label="sku名称" />
                            <el-table-column prop="tempStoreName" label="库位" />
                            <el-table-column prop="skuNum" label="sku数量" />
                            <el-table-column label="操作数量" width="170px">
                                <template #default="scopeVal">
                                    <el-input-number :controls="false" :min="0" @change="onNumberChange(scopeVal)"
                                        v-model="scopeVal.row.tempNumber" size="small"></el-input-number>
                                </template>
                            </el-table-column>
                            <el-table-column label="备注" width="200px">
                                <template #default="scopeVal">
                                    <el-input v-model="scopeVal.row.tempRemark" />
                                </template>
                            </el-table-column>
                        </el-table>
                    </template>

                </el-table-column>

                <el-table-column fixed="right" label="操作" width="150">
                    <template #default="scope">
                        <div class="operation">
                            <el-button :disabled="!isActive" @click="onUpdateItem(scope.row)" type="primary"
                                size="small">编辑</el-button>
                            <el-popover :disabled="!isActive" placement="top" width="40">
                                <p>确定删除该库存吗？</p>
                                <div style="text-align: right; margin: 0">
                                    <el-button type="primary" size="small" @click="onDeleteItem(scope.row)">确定</el-button>
                                </div>
                                <template #reference>
                                    <el-button :disabled="!isActive" type="danger" size="small"
                                        slot="reference">删除</el-button>
                                </template>

                            </el-popover>
                        </div>

                    </template>
                </el-table-column>
            </el-table>
            <br />
            <Pagination :total="dataCount" :page="current" :limit="pageSize" @pagination="onPageChange" />
        </el-card>
        <!-- 新增编辑弹窗 -->
        <el-dialog v-model="showDialog" title="操作" width="500px" @close="onClose">
            <el-form ref="formRef" :model="ruleForm" :rules="rules" label-width="120px">
                <el-form-item label="商品图片" prop="skcImageUrl">
                    <el-upload class="avatar-uploader" :action="uploadURL" :show-file-list="false"
                        :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
                        <img v-if="ruleForm.skcImageUrl" :src="ruleForm.skcImageUrl" class="avatar" />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
                <el-form-item label="商品名称" prop="skcName">
                    <el-input v-model="ruleForm.skcName" />
                </el-form-item>

                <el-form-item label="商品ID" prop="skcId">
                    <el-input v-model="ruleForm.skcId" />
                </el-form-item>
                <br />
                <p class="sku-info">
                    <span class="cup">sku信息</span>
                <div>
                    <el-button size="small" @click="onItemAdd">添加sku</el-button>
                </div>

                </p>
                <br />
                <template v-for="(item, index) of ruleForm.skuInfo" :key="index">
                    <el-form-item label="skuID" :prop="'skuInfo.' + index + '.skuId'" :rules="rules['skuId']">
                        <el-input style="width: 220px;" v-model="item.skuId" /> <el-button v-if="index >= 1" type="danger"
                            size="small" style="margin-left: 10px;" @click="onItemDel(index)">删除</el-button>
                    </el-form-item>
                    <el-form-item label="sku名称" :prop="'skuInfo.' + index + '.skuName'" :rules="rules['skuName']">
                        <el-input style="width: 220px;" v-model="item.skuName" />
                    </el-form-item>
                    <el-form-item label="数量" :prop="'skuInfo.' + index + '.skuNum'" :rules="rules['skuNum']">
                        <el-input-number style="width: 220px;" v-model="item.skuNum" :controls="false"
                            :min="0"></el-input-number>
                    </el-form-item>
                    <el-form-item label="仓库地址编号" :prop="'skuInfo.' + index + '.addressId'" :rules="rules['addressId']">
                        <el-select style="width: 220px;" v-model="item.addressId">
                            <el-option v-for="item of storeList" :key="item.addressId" :label="item.addressName"
                                :value="item.addressId" />
                        </el-select>
                    </el-form-item>
                    <br />
                </template>

            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showDialog = false">取消</el-button>
                    <el-button type="primary" @click="onSave(formRef)" :loading="submitLoading">保存</el-button>
                </div>
            </template>
        </el-dialog>

        <!-- 仓库列表弹窗 -->
        <el-dialog v-model="showStoreModal" title="仓库列表" width="700px">
            <el-row>
                <el-col :span="24">
                    <el-button type="primary" @click="onAddStore">新增仓库</el-button>
                </el-col>
            </el-row>
            <br />
            <el-table :data="storeList" stripe style="width: 100%">
                <el-table-column prop="addressId" label="ID" />
                <el-table-column prop="addressName" label="仓库名称" />
                <el-table-column prop="addressPosition" label="仓库地址" />
                <el-table-column prop="operation" label="操作">
                    <template v-slot="{ row }">
                        <el-button size="small" @click="onUpdateStore(row)">编辑</el-button>
                        <el-button size="small" type="danger" @click="onDelStore(row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showStoreModal = false">关闭</el-button>
                </div>
            </template>
        </el-dialog>
        <!-- 操作仓库列表弹窗 -->
        <el-dialog v-model="showOperModal" title="操作" width="400px" @close="onOperClose">

            <el-form ref="storeRef" :model="storeRule" class="demo-dynamic">
                <el-form-item label="仓库名称" prop="addressName"
                    :rules="{ required: true, trigger: 'blur', message: '请输入仓库名称' }">
                    <el-input v-model="storeRule.addressName" />
                </el-form-item>
                <el-form-item label="仓库地址" prop="addressPosition"
                    :rules="{ required: true, trigger: 'blur', message: '请输入仓库地址' }">
                    <el-input v-model="storeRule.addressPosition" />
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="showOperModal = false">取消</el-button>
                    <el-button @click="onSaveStore(storeRef)" type="primary">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>


<script lang="ts" setup>
import { onMounted, reactive, ref } from 'vue'
import { getInventoryListApi, addInventoryItemApi, updateInventoryItemApi, deleteInventoryItemApi, getAddressApi, addInventoryNumApi, resetInventoryNumApi, addAddressApi, updateAddressApi, deleteAddressApi } from "@/api/pdd"
import { ElMessage, ElMessageBox } from "element-plus"
import type { FormInstance, TableInstance } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/user'


interface FormDataType {
    inventoryItemId?: string | number,
    skcName: string,
    skcImageUrl: string,
    skcId: string,
    skuInfo: [{
        skuName: string,
        skuId: string,
        skuNum: string | number,
        addressId: string | number
    }]
}

interface StoreDataType {
    addressId: string | number,
    addressName: string,
    addressPosition: string
}

function formData(): FormDataType {
    return {
        inventoryItemId: '',
        skcName: '',
        skcImageUrl: '',
        skcId: '',
        skuInfo: [{
            skuName: '',
            skuId: '',
            skuNum: '',
            addressId: ''
        }]
    }
}

function storeData(): StoreDataType {
    return {
        addressId: '',
        addressName: '',
        addressPosition: ''
    }
}

const inventoryList = ref([]);
const current = ref(1);
const pageSize = ref(10)
const skcFilter = ref('');
const curFilter = ref('');
const curOptions = ref([{ value: 30, label: '30' }, { value: 60, label: '90' }, { value: 180, label: '180' }]);
const dataCount = ref(0)
const inventoryCount = ref(0)
const showDialog = ref(false)
const formRef = ref<FormInstance>();
const uploadURL = ref(`${import.meta.env.MODE === 'development' ? '/api' : ''}/api/uploadResource`)
const submitLoading = ref(false)
const selectedItemList = ref([])
const tableRef = ref<TableInstance>()
const storeRef = ref<FormInstance>()
const storeList = ref([])
const showStoreModal = ref(false)
const showOperModal = ref(false)
const isActive = ref(false) // 是否激活账户
const rules = ref({
    skcName: [{ required: true, trigger: 'blur', message: '请输入商品名称' }],
    skcImageUrl: [{ required: true, trigger: 'blur', message: '请上传商品图片' }],
    skcId: [{ required: true, trigger: 'blur', message: '请输入商品ID' }],
    skuName: [{ required: true, trigger: 'blur', message: '请输入sku名称' }],
    skuId: [{ required: true, trigger: 'blur', message: '请输入skuID' }],
    skuNum: [{ required: true, trigger: 'blur', message: '请输入sku数量' }],
    addressId: [{ required: true, trigger: 'blur', message: '请输入仓库地址编号' }]
})

const storeFilter = ref('');

// 表单
const ruleForm = reactive<FormDataType>(formData())
// 仓库表单
const storeRule = reactive<StoreDataType>(storeData())


function onClear() {

    tableRef.value.clearSelection()
}

function onUpdateStore(r) {
    storeRule.addressId = r.addressId
    storeRule.addressName = r.addressName
    storeRule.addressPosition = r.addressPosition
    showOperModal.value = true;
}

function onDelStore(r) {
    ElMessageBox.confirm('确定删除该仓库吗？').then(async () => {
        const result = await deleteAddressApi({ addressId: r.addressId });
        if (result.status === 0) {
            ElMessage.success('已删除');
            getStoreList();
            showOperModal.value = false;
        }
    })
}

function onSaveStore(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            if (storeRule.addressId) {
                storeUpdate()
            } else {
                storeAddData()
            }
        } else {
            return false
        }
    })
}

function onOperClose() {
    storeRef.value.resetFields()
    storeRef.value.clearValidate()
    Object.assign(storeRule, storeData())
}

// 获取仓库地址列表
async function getStoreList() {
    const result: any = await getAddressApi();
    if (result.status === 0) {
        storeList.value = result.addressList;
        getInventoryList();

    }
}

function onAddStore() {
    showOperModal.value = true;
}

// 覆盖库存
async function resetInventory() {
    // 覆盖库存的数量只能是整数
    const tempParam = getParam('add')
    if (tempParam.length === 0) {
        return
    }
    const less = tempParam.every((item: any) => {
        return item.num >= 0;
    })
    if (less.length === 0) {
        ElMessage.error('覆盖库存数量不能为负数，请检查后提交。')
        selectedItemList.value = []
        tableRef.value.clearSelection()
        return;
    }
    try {
        const result = await resetInventoryNumApi({
            setInfoList: tempParam
        });
        if (result.status === 0) {
            ElMessage.success('操作成功')
            current.value = 1
            getInventoryList()
        }
        selectedItemList.value = []
        tableRef.value.clearSelection()
    } catch {
        selectedItemList.value = []
        tableRef.value.clearSelection()
    }
}

// 入库
function addInventory() {
    const tempParam = getParam('add')
    if (tempParam.length > 0) {
        operStore(tempParam)

    }
}
// 出库
function reduceInventory() {
    const tempParam = getParam('reduce')
    if (tempParam.length > 0) {
        operStore(tempParam)

    }
}

// 组装参数
function getParam(t) {
    const param = selectedItemList.value.map(item => {
        return item.skuInfo.map((val, index) => {
            if (!val.tempNumber && !val.tempRemark) {
                return null;
            }
            if (t === 'reduce' && val.tempNumber > val.skuNum) {
                ElMessage.error('出库数量不能大于sku数量')
                return null
            }
            return {
                inventoryItemId: item.inventoryItemId,
                inventoryItemSkuId: index,
                num: t === 'reduce' ? (val.tempNumber * -1) ?? (val.skuNum * -1) : val.tempNumber ?? val.skuNum,
                comments: val.tempRemark || ''
            }
        }).filter(item => item)
    });
    return param[0]
}

// 操作sku库存 
async function operStore(param) {
    try {
        const result = await addInventoryNumApi({
            addInfoList: param
        });
        if (result.status === 0) {
            ElMessage.success('操作成功')
            current.value = 1
            getInventoryList()
        }
        selectedItemList.value = []
        tableRef.value.clearSelection()
    } catch {
        selectedItemList.value = []
        tableRef.value.clearSelection()
    }

}

// 操作数量改变
function onNumberChange({ row }) {
    // 得到输入的number数来计算
    const numResult = row.skuNum + row.tempNumber;
    // 输入的数量超过了数据的数量
    if (numResult < 0) {
        // 直接把所有数量默认填进去
        row.tempNumber = row.skuNum * (-1);
    }
}

function handleSelectionChange(val: FormDataType[]) {
    if (val && val.length) {
        selectedItemList.value = val;
    }
}

function onClose() {
    formRef.value.resetFields()
    formRef.value.clearValidate()
    Object.assign(ruleForm, formData())
}
// 编辑仓库接口
async function storeUpdate() {
    const result = await updateAddressApi(storeRule);
    if (result.status === 0) {
        ElMessage.success('已更新');
        getStoreList()
    }
    showOperModal.value = false;
}
// 新增仓库接口
async function storeAddData() {
    const result = await addAddressApi({ addressName: storeRule.addressName, addressPosition: storeRule.addressPosition });
    if (result.status === 0) {
        ElMessage.success('已添加');
        getStoreList()
    }
    showOperModal.value = false;
}
// 新增仓库
async function onStoreAdd() {
    showStoreModal.value = true;
}

function onItemAdd() {
    ruleForm.skuInfo.push({
        skuName: '',
        skuId: '',
        skuNum: '',
        addressId: ''
    });
}

function handleAvatarSuccess(e) {
    if (e.status === 0) {
        ruleForm.skcImageUrl = e.resourceUrl;
    }
}

function beforeAvatarUpload(e) {
    const is5M = (e.size / 1024 / 1024) > 5;
    if (is5M) {
        ElMessage.error('商品图片不能大于5M，请压缩后上传');
        return;
    }
}

function onItemDel(index) {
    ruleForm.skuInfo.splice(index, 1);
}

// 设置table样式
function tableRowStyle({ row, rowIndex }) {
    // return 'background:red;'
}

// edit
async function editInventoryItem() {
    try {
        const param = {
            inventoryItemId: ruleForm.inventoryItemId,
            inventoryItemInfo: {
                skcName: ruleForm.skcName,
                skcImageUrl: ruleForm.skcImageUrl,
                skcId: ruleForm.skcId,
                skuInfo: ruleForm.skuInfo,
            }
        }
        const result = await updateInventoryItemApi(param);
        if (result.status === 0) {
            current.value = 1;
            getInventoryList();
            ElMessage.success('已编辑');
            showDialog.value = false;
        }
        submitLoading.value = false;
    } catch {
        submitLoading.value = false;
    }
}

// 增加库存
async function addInventoryItem() {

    try {
        const result = await addInventoryItemApi(ruleForm);
        if (result.status === 0) {
            current.value = 1;
            getInventoryList();
            ElMessage.success('已添加');
            showDialog.value = false;
        }
        submitLoading.value = false;
    } catch {
        submitLoading.value = false;

    }
}


function onSave(formEl: FormInstance | undefined) {
    if (!formEl) return;
    formEl.validate((valid) => {
        if (valid) {
            submitLoading.value = true
            ruleForm.skuInfo.forEach(item => {
                item.skuNum = +item.skuNum
                item.addressId = +item.addressId
            })
            if (ruleForm.inventoryItemId) {
                editInventoryItem()
            } else {
                delete ruleForm.inventoryItemId
                addInventoryItem()

            }
        } else {
            return false
        }
    })
}

function onAdd() {
    showDialog.value = true;
}

// 获取库存列表数据
async function getInventoryList() {

    let param = { pageId: current.value, pageSize: pageSize.value, filter: {} }
    if (skcFilter.value) {
        param.filter.skcId = skcFilter.value;
    }
    if (curFilter.value) {
        param.filter.recentDayLimit = curFilter.value;
    }
    if (storeFilter.value) {
        param.filter.inventoryAddressId = storeFilter.value;
    }
    const result = await getInventoryListApi(param);
    if (+result.status === 0) {
        result.inventoryItemInfoList.forEach((item, index) => {
            item.skuInfo.forEach((vals) => {
                vals.tempNumber = null
                vals.tempRemark = ''
                // 保存数据下标
                vals.rowIndex = index;
                const tempStore = storeList.value.find(storeData => +storeData.addressId === vals.addressId)
                if (tempStore) {
                    vals.tempStoreName = tempStore.addressName
                } else {
                    vals.tempStoreName = ''
                }
            })
        })
        // 成功
        inventoryList.value = result.inventoryItemInfoList
        dataCount.value = result.inventoryItemNum
        inventoryCount.value = result.inventoryItemSkuStoreNum
    } else {
        ElMessage.info(result.errorMsg);
    }
}

async function onDeleteItem(row) {
    const result = await deleteInventoryItemApi({ inventoryItemId: row.inventoryItemId })
    if (result.status === 0) {
        ElMessage.success('已删除')
        current.value = 1
        getInventoryList()
    }
}

function onUpdateItem(row) {
    ruleForm.inventoryItemId = +row.inventoryItemId
    ruleForm.skcId = row.skcId
    ruleForm.skcName = row.skcName
    ruleForm.skcImageUrl = row.skcImageUrl
    ruleForm.skuInfo = row.skuInfo
    showDialog.value = true;
}

function onPageChange({ page, limit }) {
    current.value = page || 1;
    pageSize.value = limit
    getInventoryList()
}

// 重置
function onReset() {
    skcFilter.value = ''
    curFilter.value = ''
    storeFilter.value = ''
    getInventoryList();
}

onMounted(() => {
    const userStore = useUserStore()
    isActive.value = Boolean((userStore.sysUser as any).user_level)
    getStoreList()
})

</script>

<style lang="scss" scoped>
.inventory-container::v-deep .el-table__body {
    width: 100% !important;
}

.sku-info {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.avatar-uploader-icon {
    width: 120px;
    height: 120px;
    border: 1px dashed #ccc;
    border-radius: 10px;

}

.avatar {
    width: 120px;
    height: 120px;
    border-radius: 10px;
}

.skc-data {
    width: 100%;
    display: flex;

    .skc-img {
        width: 60px;
        height: 60px;
        border-radius: 5px;
        margin-right: 10px;
    }

    .skc-line {
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

}

.operation {
    display: flex;
    align-items: center;
}
</style>